import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/bean/user_info.dart';
import 'package:flutter_bsbdj/bmob/bmob/bmob_file_manager.dart';
import 'package:flutter_bsbdj/bmob/bmob/bmob_query.dart';
import 'package:flutter_bsbdj/bmob/bmob/response/bmob_error.dart';
import 'package:flutter_bsbdj/bmob/bmob/type/bmob_file.dart';

import 'package:flutter_bsbdj/utils/shared_preferences_util.dart';
import 'package:flutter_bsbdj/utils/constant.dart';
import 'package:flutter_bsbdj/utils/toast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:flutter_bsbdj/bmob/utils/dialog_util.dart';


class UpLoadHeader extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return LoadWidget();
  }

}

class LoadWidget extends State<UpLoadHeader>{

  File photo;
  String pic="";
  bool _upLoad=false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SharedPrefrenceUtil.getStringValue(Constant.USER_PIC, "").then((header){
      if(header.isNotEmpty){
        setState(() {
          pic=header;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("头像上传"),
        actions: <Widget>[
          IconButton(icon: Icon(Icons.photo,color: Colors.white,), onPressed: (){
            _choosePhoto();
          }),
          IconButton(icon: Icon(Icons.camera_alt,color: Colors.white,),onPressed: (){
            _takePhoto();
          },)
        ],
      ),
      body: Stack(
        children: <Widget>[
          Column(
            children: <Widget>[
              Expanded(child: Container(
                alignment: Alignment.center,
                child: photo==null?(pic==""?Container():Image.network(pic)):GestureDetector(
                  child: Image.file(photo),
                  onTap: (){
                    _copImage(photo);
                  },
                ),
              )),
              Container(
                alignment: Alignment.center,
                child: MaterialButton(onPressed: (){
                  if(photo==null){
                    Toast.toast(context, "请选择图片!");
                  }else{
                    _upLoadFile();
                  }
                },
                  child: Text("上传头像",style: TextStyle(color: Colors.white),),
                  minWidth: 300,
                  color: Colors.blueAccent,),
              )

            ],
          ),
          _upLoad?Container(
            alignment: Alignment.center,
            child: Container(
              width: 200,
              height: 200,
              child: Image.asset("images/ic_loading.gif"),
            ),
          ):Container(width: 0,height: 0,),
        ],
      )
    );
  }

  //选择图片
  void _choosePhoto() async{
    await ImagePicker.pickImage(source: ImageSource.gallery).then((file){
      if(file!=null){
        _copImage(file);
      }
    });
  }

  //拍照
  void _takePhoto() async{
    await ImagePicker.pickImage(source: ImageSource.camera).then((file){
      if(file!=null){
        setState(() {
          photo=file;
        });
      }
    });
  }

  //图片剪裁
  void _copImage(File file)async{
        await ImageCropper.cropImage(sourcePath: file.path,
        ratioX: 1.0,
        ratioY: 1.0,).then((fileCop){
          if(fileCop!=null) {
            changePhoto(fileCop);
          }else{
            changePhoto(file);
          }
        }).catchError((e){
          changePhoto(file);
        });
  }

  //setState
  void changePhoto(File file){
    setState(() {
      photo=file;
    });
  }

  //文件上传
  void _upLoadFile()async{
    _uploadChange();
    //先查询是否已有头像
    await SharedPrefrenceUtil.getStringValue(Constant.USER_ID, "").then((id){
      if(id!=""){
        BmobQuery<UserInfoBean> query=BmobQuery();
        query.addWhereEqualTo("userId", id);
        query.queryObjects().then((datas){
          if(datas==null||datas.length==0){
            _sendFile(id,"null");
          }else{
            List<UserInfoBean> infos=datas.map((i)=>UserInfoBean.fromJson(i)).toList();
            _sendFile(id,infos[0].objectId);
          }
        }).catchError((e){
          _uploadChange();
          print(BmobError.convert(e).toString());
        });
      }else{
        //理论上不存在此种情况
        _uploadChange();
      }
    });
  }

  void _sendFile(String userId,String objectId)async{
    await BmobFileManager.upload(photo).then((bmobFile){
      var userInfo=UserInfoBean();
      userInfo.userId=userId;
      userInfo.pic=bmobFile.url;
      if(objectId=="null") {
        userInfo.save().then((saved){
          _uploadSuccess(userInfo.pic);
        }).catchError((e){
          _uploadChange();
          print(BmobError.convert(e).toString());
        });
      }else{
        userInfo.objectId = objectId;
        userInfo.update().then((updated){
          _uploadSuccess(userInfo.pic);
        }).catchError((e){
          _uploadChange();
          print(BmobError.convert(e).toString());
        });
      }
    }).catchError((e){
      _uploadChange();
      showError(context, BmobError.convert(e).toString());
    });
  }

  void _uploadSuccess(String pic){
    _uploadChange();
    SharedPrefrenceUtil.setStringValue(Constant.USER_PIC, pic);
    Navigator.of(context).pop(pic);
  }

  void _uploadChange(){
    setState(() {
      _upLoad=!_upLoad;
    });
  }

}